package fx.componet;

import fx.protocol.PlayAble;
import fx.protocol.Propertify;
import fx.protocol.Scheduled;
import javafx.application.Platform;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.util.Duration;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MyMediaView extends MediaView implements PlayAble, Scheduled {
    private boolean isPlaying = false;
    private MediaPlayer player;
    private List<Propertify> eleList = new ArrayList<>();

    public MyMediaView(MediaPlayer mediaPlayer) {
        super(mediaPlayer);
        this.player = mediaPlayer;
    }

    public void setPlayer(MediaPlayer player) {
        Runnable onEndOfMedia = player.getOnEndOfMedia();
        setMediaPlayer(player);
        player.setOnEndOfMedia(onEndOfMedia);
        this.player = player;
    }

    public void setPlaying(boolean playing) {
        isPlaying = playing;
    }

    @Override
    public void doPlay() {
        if (!isPlaying) {
            player.play();
        } else {
            player.pause();
        }
        isPlaying = !isPlaying;
    }

    @Override
    public void schedule() {
        new Timer(true).scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(() -> {
                    System.out.println("更新进度 ...");
                    Duration currentTime = player.getCurrentTime();
                    Duration mediaPlayerTotalDuration = player.getTotalDuration();
                    if (eleList.size() > 2) {
                        eleList.get(0).update(currentTime.toSeconds() / mediaPlayerTotalDuration.toSeconds());
                        eleList.get(1).update((int) currentTime.toSeconds() + "");
                        eleList.get(2).update((int) mediaPlayerTotalDuration.toSeconds() + "");
                    }
                });
            }
        }, 0, 1000);
    }

    @Override
    public List<Propertify> needUpdateEleList(Propertify... nodeList) {
        for (Propertify propertify : nodeList) {
            eleList.add(propertify);
        }
        return eleList;
    }
}
